package com.kaifamiao.tracking.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/cookie/counter")
public class CookieCounterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 约定表示计数器的cookie的名称
        final String cookeName = "counter";
        int count = 0;
        // 尝试从请求头中获得所有的cookie
        Cookie[] cookies = request.getCookies();
        if( cookies != null && cookies.length != 0 ){
            for ( Cookie c : cookies ) {
                if( cookeName.equals( c.getName() ) ){
                    String value = c.getValue();
                    count = Integer.parseInt( value );
                    break;
                }
            }
        }

        Cookie cookie = new Cookie( cookeName, ++count + "" );
        response.addCookie( cookie );

        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();

        out.println( "<h3 style='text-align: center'>");
        out.println( count );
        out.println( "</h3>");
    }

}
